package com.daou.meeting.controller;

import java.util.List;
import java.util.Locale;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.daou.meeting.domain.User;
import com.daou.meeting.service.UserService;
import com.daou.meeting.xmpp.Xmpp;
import com.daou.meeting.xmpp.XmppImpl;
import com.daou.meeting.xmpp.XmppReceiver;

@Controller
public class LoginController {
	
	private class Receiver implements XmppReceiver {
		
		@Override
		public void receivePageIndex(int pageIdx) {
			System.out.println(pageIdx);
			ScriptEngineManager manager = new ScriptEngineManager();  
	        ScriptEngine engine = manager.getEngineByName("JavaScript");
	        
	        String script = "function hello(name) { print('Hello, ' + name); }";  
	        try {
				engine.eval(script);
			} catch (ScriptException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}  
	  
	        Invocable inv = (Invocable) engine;  
	        try {
				inv.invokeFunction("hello", "Scripting!!" );
			} catch (NoSuchMethodException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ScriptException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
		}
	}
	
	@Autowired
	private UserService userService;
	
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String home(Locale locale, Model model, HttpServletRequest request) {
        return "login";
    }
    
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(Locale locale, Model model, HttpServletRequest request,
    		@RequestParam(value="email", required=true) String email,
    		@RequestParam(value="password", required=true) String password) {
    	
    	
    	User user = userService.login(email, password);    	
    	
    	if(user != null) {
    		user.setOnline(true);
    		userService.updateUser(user);
    		XmppReceiver receiver = new Receiver();
    		Xmpp xmpp = new XmppImpl(receiver);
    		// When
    		xmpp.connection(user.getName());
    		request.setAttribute("name", user.getName());
    		request.setAttribute("email", user.getEmail());
    		return "home";
    	} else {
    		return "login";
    		
    	}
    }
    
    @RequestMapping(value = "/online", method = RequestMethod.GET)
    public String login(Locale locale, Model model, HttpServletRequest request) {
    	List<User> users = userService.onlineUser();
    	request.setAttribute("users", users);
    	return "online";
    }
	
}
